package common;

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import db.Connector;
import db.MySqlConnector;

public class DBHelper
{

    final static String DB_VAR_PREFIX = "database";
    Map<String, Connector> connectorMap = new HashMap<String, Connector>();
    private static DBHelper instance;

    private DBHelper() throws Exception
    {
        init();
    }

    public static DBHelper get()
    {
        if (null == instance)
        {
            try
            {
                instance = new DBHelper();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return instance;
    }

    public static Connector getConnector(String name)
    {
        DBHelper helper = get();
        if (!helper.connectorMap.containsKey(name))
        {
            throw new RuntimeException(String.format("Can't find this connetor : %s", name));
        }
        return helper.connectorMap.get(name);
    }

    void init() throws Exception
    {
        String dbSchames = DB_VAR_PREFIX + ".schames";
        String allSchames = ConfigHelper.getStringProperty(dbSchames);
        if (StringUtils.isBlank(allSchames))
        {
            throw new java.lang.RuntimeException(String.format("the %s parameter isn't exist.", dbSchames));
        }
        String[] names = StringUtils.splitByWholeSeparator(allSchames, ",");
        synchronized (this)
        {
            for (String connectorName : names)
            {
                connectorName = StringUtils.trimToNull(connectorName);
                Connector conn = loadConnecttor(connectorName);
                connectorMap.put(connectorName, conn);
            }
        }

    }

    public static void main(String[] args)
    {
        String arg = "aa  , adadf,adff  ,, ,adsfadf";
        String[] aa = StringUtils.splitByWholeSeparator(arg, ",");
        for (String a : aa)
        {
            System.out.println(String.format("\"%s\"", a));
        }
    }

    Connector loadConnecttor(String name) throws Exception
    {
        String dbVarPrefix = DB_VAR_PREFIX + ".";
        String url = ConfigHelper.getStringProperty(dbVarPrefix + name + ".url");
        String username = ConfigHelper.getStringProperty(dbVarPrefix + name + ".user");
        String password = ConfigHelper.getStringProperty(dbVarPrefix + name + ".password");
        String options = ConfigHelper.getStringProperty(dbVarPrefix + name + ".options", "");
        int poolSize = ConfigHelper.getNumberProperty(dbVarPrefix + name + ".poolSize");
        int timeoutInMs = ConfigHelper.getNumberProperty(dbVarPrefix + name + ".timeout", 100000);
        int connectionTimeoutInSec =
                        ConfigHelper.getNumberProperty(dbVarPrefix + name + ".connectionTimeout", 10);
        int idleOpenTimeoutInMs =
                        ConfigHelper.getNumberProperty(dbVarPrefix + name + ".idleOpenTimeout",
                            1000 * 60 * 60 /* 1 hour */);
        int selectTimeoutSec =
                        ConfigHelper.getNumberProperty(dbVarPrefix + name + ".selectTimeoutSec",
                            0);
        int updateTimeoutSec =
                        ConfigHelper.getNumberProperty(dbVarPrefix + name + ".updateTimeoutSec",
                            0);
        return loadConnector(name, url, username, password, options, poolSize, timeoutInMs,
            connectionTimeoutInSec, idleOpenTimeoutInMs, selectTimeoutSec, updateTimeoutSec);
    }

    Connector loadConnector(String name, String url, String username, String password, String options,
                    int poolSize, int timeoutInMs, int connectionTimeoutInSec,
                    int idleOpenTimeInMs, int selectTimeoutSec, int updateTimeoutSec)
                    throws Exception
    {
        String host = null;
        int port = 0;
        try
        {
            host = url.substring(url.indexOf("//") + 2, url.lastIndexOf(":"));
        }
        catch (IndexOutOfBoundsException ex)
        {
            logInfo("loadConnector: could not determine the host form url=" + url);
            throw ex;
        }

        try
        {
            port = Integer.parseInt(url.substring(url.lastIndexOf(":") + 1, url.lastIndexOf("/")));
        }
        catch (IndexOutOfBoundsException ex)
        {
            logInfo("loadConnector: could not determine the port form url=" + url);
            throw ex;
        }

        String database = url.substring(url.lastIndexOf("/") + 1, url.length());
        String provider = url.substring(url.indexOf(":") + 1, url.lastIndexOf(":/"));
        Connector connector;
        if (provider.equals("mysql"))
        {
            connector = new MySqlConnector(name, host, port,
                            database, options, username, password, poolSize, timeoutInMs,
                            connectionTimeoutInSec, idleOpenTimeInMs, selectTimeoutSec, updateTimeoutSec);
        }
        else
        {
            throw new Exception("Unknown provider: " + provider);
        }
        return connector;
    }

    public void logInfo(String log)
    {

    }
}
